/*
 * dll_manager.cpp
 *
 *  Created on: Nov 2, 2012
 *      Author: khanhhh
 */

/*
 * ipvn_service.cpp
 *
 *  Created on: Oct 19, 2012
 *      Author: khanhhh
 */

#ifndef IPVN_SERVICE_CPP_
#define IPVN_SERVICE_CPP_
extern "C" {
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lauxlib.h>
#include <luajit-2.0/lualib.h>
}

#include "../lua_interaction/luna.hpp"
#include "dll_manager.hpp"
#include <iostream>
namespace http {
namespace server3 {

const char dll_manager::className[] = "dll_manager";
static unsigned int BUF_SIZE = 1024;
#define method(class, name) {#name, &class::name}
Luna<dll_manager>::RegType dll_manager::methods[] = {
		method(dll_manager, get_function), { 0, 0 }
};
dll_manager::dll_manager(lua_State *L) {
	// string to get dynamic lib names
	string dll_path;
	char in_buf[BUF_SIZE]; // input buffer for lib names
	if (lua_gettop(L) >= 1) {
		if (lua_isstring(L, 1)) {
			string command_str = "ls "; // command
			dll_path = lua_tostring(L, 1);
			if (dll_path.at(dll_path.length()-1)!='/')
				dll_path.append("/");
			command_str.append(dll_path);
			command_str.append("*.so");
			// get the names of all the dynamic libs (.so files) in the current dir
			dl = popen(command_str.c_str(), "r");
			if (!dl) {
				perror("popen");
			}
			void *dlib;
			string dll_name;
			while (fgets(in_buf, BUF_SIZE, dl)) {
				dll_name = dll_path;
				// trim off the whitespace
				char *ws = strpbrk(in_buf, " \t\n");
				if (ws)
					*ws = '\0';
				// append ./ to the front of the lib name
				dll_name.append(ws);
				dlib = dlopen(dll_name.c_str(), RTLD_NOW);
				if (dlib == NULL) {
					cerr << dlerror() << endl;
				}
				// add the handle to our list
				dl_list.insert(dl_list.end(), dlib);
			}
		}
	}
}
dll_manager::~dll_manager() {
}
int dll_manager::get_function(lua_State *L) {
	return 0;
}

}
}
#endif /* IPVN_SERVICE_CPP_ */
